/*
 * Copyright (C) 2015 kmy-framework-base Project
 *               Author: Administrator
 *               Date: 2015年11月4日
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.zmq.ha.client.listner;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rabbitmq.client.ShutdownListener;
import com.rabbitmq.client.ShutdownSignalException;
import com.zmq.ha.client.core.ConnectionWrapper;
import com.zmq.ha.client.exceptions.Exceptions;

public class MyConnectionShutdownListener implements ShutdownListener {
	
	private static final Logger logger = LoggerFactory.getLogger(MyConnectionShutdownListener.class);
	
	private final ConnectionWrapper connectionHandler;
	

	public MyConnectionShutdownListener(ConnectionWrapper connectionHandler) {
		super();
		this.connectionHandler = connectionHandler;
	}

	@SuppressWarnings("static-access")
	@Override
	public void shutdownCompleted(ShutdownSignalException cause) {
		connectionHandler.isRecovery = true;
		connectionHandler.connectionShutdown();
		//非程序自动关闭RMQ连接
		if( !cause.isInitiatedByApplication() ){
			connectionHandler.COMSUMER_EXECUTRO.execute(new Runnable() {
				@Override
				public void run() {
					logger.info("RMQ : occur connectionShutDown, begin recover connection...");
					try {
						connectionHandler.recoveryConnection();
					} catch (Exception e) {
						if( !Exceptions.isCausedByConnectionClosure(e) ){
							logger.info("RMQ : occur  unconnectionClosure, begin close connection...");
							connectionHandler.connectionClose();
						}
					}
				}
			});
			
		} else{
			logger.info("RMQ : occur normal connection close");
			connectionHandler.connectionClose();
		}

	}
	
	
	
	

}
